# Create your views here.
import time
import traceback
from threading import Thread

from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.views import generic

from . import CsShare
from .models import ShareInfo
import requests


class IndexView(generic.ListView):
    template_name = "cs/index.html"

    context_object_name = "latest_share_list"

    def get_queryset(self):
        url = "https://d3qx0f55wsubto.cloudfront.net/api/bbs-article?cat_id=0&page_size=20&page=1&lang=1"

        payload = {}
        headers = {}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.json())
        jsonData = response.json()['data']['data']
        for item in jsonData:
            print(item['id'])
            shareInfo = ShareInfo.objects.filter(share_id=item['id'])
            if shareInfo.exists():
                shareInfo = shareInfo.first()
                print("exists==", shareInfo)
                shareInfo.updated_at = item['updated_at']
                shareInfo.save()
            else:
                share = ShareInfo(share_title=item['title'], share_id=item['id'], share_user=item['user'],
                                  updated_at=item['updated_at'], )
                share.save()
        """
    Return the last five published questions (not including those set to be
    published in the future).
    """
        return ShareInfo.objects.filter(share_lang=1, updated_at__lte=timezone.now()).order_by("-updated_at")[:20]


class IndexViewEn(generic.ListView):
    template_name = "cs/index.html"

    context_object_name = "latest_share_list"

    def get_queryset(self):
        url = "https://d3qx0f55wsubto.cloudfront.net/api/bbs-article?cat_id=0&page_size=20&page=1&lang=0"

        payload = {}
        headers = {}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)
        jsonData = response.json()['data']['data']
        for item in jsonData:
            print(item['id'])
            shareInfo = ShareInfo.objects.filter(share_id=item['id'])
            if shareInfo.exists():
                print("exists==", shareInfo)
                shareInfo = shareInfo.first()
                shareInfo.updated_at = item['updated_at']
                shareInfo.save()
            else:
                share = ShareInfo(share_title=item['title'], share_id=item['id'], share_user=item['user'],
                                  updated_at=item['updated_at'], share_lang=0, )
                share.save()
                """
            Return the last five published questions (not including those set to be
            published in the future).
            """
        return ShareInfo.objects.filter(share_lang=0, updated_at__lte=timezone.now()).order_by("-updated_at")[:20]


def share(request, share_id):
    print('正在分享', share_id)
    mTitle = request.POST["share_title"]
    mShare = ShareInfo.objects.filter(share_num=-1)
    if mShare.exists():
        return HttpResponse("上次的分享《" + mShare.first().share_title + "》正在进行,如果长时间无法正常分享请联系dongyang")
    mShare = ShareInfo.objects.filter(share_num=1)
    if mShare.exists():
        # try:
        #     mShare = mShare.order_by("-share_date")[:3]
        #     print(mShare)
        #     print(mShare[2])
        #     print(mShare[2].was_shared_recently())
        #     if mShare[2].was_shared_recently():
        #         return HttpResponse("1天内限制分享3次,如果有疑问请联系dongyang")
        # except:
        #     print(traceback.format_exc())
        #     pass
        mShare = mShare.order_by("-share_date")
        mShare = mShare.first()
        print(mShare.was_shared_recently())
        if mShare.was_shared_recently():
            return HttpResponse("1天内限制分享1次,如果有疑问请联系dongyang")
    share = get_object_or_404(ShareInfo, share_id=share_id)
    if share.share_num == 0 or share.share_num == 2:
        share.share_num = -1
        share.save()
        t = Thread(target=task, args=('子线程', mTitle))
        t.start()
        return HttpResponse('正在分享:《' + mTitle + "》")
    elif share.share_num == -1:
        return HttpResponse('正在分享:《' + mTitle + "》")
    elif share.share_num == 1:
        return HttpResponse('分享完成:《' + mTitle + "》")


def task(name, title):
    try:
        print('%s is runing ' % name)
        share = ShareInfo.objects.filter(share_title=title).first()
        lang_type = share.share_lang
        CsShare.share(title, lang_type)
        print('___执行完毕,更新数据库')
        share.share_num = 1
        share.share_date = timezone.now()
        share.save()
        print('%s is done' % name)
    except Exception as e:
        print('e-----:', e)
        print(traceback.format_exc())
        share.share_num = 2
        share.share_date = timezone.now()
        share.save()
        pass
